package com.fjh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjh.dao.ProEsDao;
import com.fjh.domain.ProdComm;
import com.fjh.domain.ProdTagReference;
import com.fjh.domain.Sku;
import com.fjh.mapper.ProdTagReferenceMapper;
import com.fjh.mapper.SkuMapper;
import com.fjh.model.EsChange;
import com.fjh.model.SkuChange;
import com.fjh.model.StockChange;
import com.fjh.service.ProdCommService;
import com.fjh.service.ProdTagReferenceService;
import com.fjh.service.SkuService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.domain.Prod;
import com.fjh.mapper.ProdMapper;
import com.fjh.service.ProdService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
@Slf4j
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{
    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdCommService prodCommService;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 分页查询
     * @param page
     * @param prod
     * @return
     */
    @Override
    public Page<Prod> loadProdPage(Page<Prod> page, Prod prod) {
        return prodMapper.selectPage(page,new LambdaQueryWrapper<Prod>()
                .eq(!ObjectUtils.isEmpty(prod.getStatus()), Prod::getStatus, prod.getStatus())
                .like(StringUtils.hasText(prod.getProdName()),Prod::getProdName,prod.getProdName())
                .orderByDesc(Prod::getCreateTime)
        );
    }

    /**
     * 根据时间区间查询商品数量
     * @param t1
     * @param t2
     * @return
     */
    @Override
    public Integer totalCount(Date t1, Date  t2) {
        return prodMapper.selectCount(new LambdaQueryWrapper<Prod>()
                .between(t1 != null && t2 != null,Prod::getUpdateTime,t1,t2)
        );
    }

    /**
     * 分页查询需要导入es的商品
     * 1.需要分页查询数据库 拿到商品集合
     * 2.处理一些属性 标签分组 的ids
     * 3.处理评论
     * @param page
     * @param t1
     * @param t2
     * @return
     */
    @Override
    public List<Prod> findProdToEs(Page<Prod> page, Date t1, Date t2) {
        Page<Prod> prodPage = prodMapper.selectPage(page, new LambdaQueryWrapper<Prod>()
                .between(t1 != null && t2 != null, Prod::getUpdateTime, t1, t2)
        );
        List<Prod> prodList = prodPage.getRecords();
        if (CollectionUtils.isEmpty(prodList)){
            return Collections.emptyList();
        }
        //先处理标签分组
        //1.先拿到商品的ids
        List<Long> prodIds = prodList.stream()
                .map(Prod::getProdId)
                .collect(Collectors.toList());
        //2.再查标签关系表
        List<ProdTagReference> tagReferenceList = prodTagReferenceService.list(new LambdaQueryWrapper<ProdTagReference>()
                .in(ProdTagReference::getProdId, prodIds)
                .eq(ProdTagReference::getStatus, 1)
        );
        if (!CollectionUtils.isEmpty(tagReferenceList)){
            //说明有标签，处理标签
            //循环商品集合  处理标签集合  拿到prodId相同的标签 收集起来
            prodList.forEach(prod -> {
                List<Long> tagList = tagReferenceList.stream()
                        .filter(prodTagReference -> prodTagReference.getProdId().equals(prod.getProdId()))
                        .map(ProdTagReference::getTagId)
                        .collect(Collectors.toList());
                prod.setTagList(tagList);
            });
        }
        //处理评论
        //from prod_comm where prodId in ids
        List<ProdComm> prodCommList = prodCommService.list(new LambdaQueryWrapper<ProdComm>()
                .in(ProdComm::getProdId, prodIds)
                .eq(ProdComm::getStatus, 1)
        );
        //循环商品  组装对应的评论
        prodList.forEach(prod -> {
            boolean flag = true;
            //判断所有的评论
            if (!CollectionUtils.isEmpty(prodCommList)){
                //找到对应商品的评论集合
                List<ProdComm> oneProdComm = prodCommList.stream()
                        .filter(prodComm -> prodComm.getProdId().equals(prod.getProdId()))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(oneProdComm)){
                    //该商品有评论
                    //拿到好评数
                    long goodsCount = oneProdComm.stream()
                            .filter(prodComm -> prodComm.getEvaluate().equals(0))
                            .count();
                    if (goodsCount !=0L){
                        flag = false;
                        //计算好评
                        int allComm = oneProdComm.size();
                        //使用好评数/总评数
                        BigDecimal goodLv = new BigDecimal(goodsCount)
                                .divide(new BigDecimal(allComm), 2, BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal(100));
                        //设置好评率和好评数
                        prod.setPraiseNumber(goodsCount);
                        prod.setPositiveRating(goodLv);
                    }
                }
            }
            if (flag){
                prod.setPraiseNumber(0L);
                prod.setPositiveRating(BigDecimal.ZERO);
            }
        });
        return prodList;
    }

    /**
     * 根据商品的id查询前台商品信息
     * 1.查商品表
     * 2.查sku表
     * 3.组装数据
     * @param prodId
     * @return
     */
    @Override
    public Prod findFrontProdSku(Long prodId) {
        Prod prod = prodMapper.selectById(prodId);
        if (!ObjectUtils.isEmpty(prod)){
            //查询商品表
            List<Sku> skuList = skuService.list(new LambdaQueryWrapper<Sku>()
                    .eq(Sku::getProdId, prod)
                    .eq(Sku::getStatus, 1)
            );
            prod.setSkuList(skuList);
        }
        return prod;
    }

    /**
     * 修改prod和sku的库存
     * @param stockChange
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void changeStock(StockChange stockChange) {
        List<EsChange> prodData = stockChange.getEsChanges();
        List<SkuChange> skuData = stockChange.getSkuChanges();
        if (CollectionUtils.isEmpty(prodData) || CollectionUtils.isEmpty(skuData)){
            return;
        }
        //处理sku库存
        skuData.forEach(skuChange -> {
            Integer i = skuMapper.changeSkuStock(skuChange.getSkuId(), skuChange.getCount());
            if (i == 0){
                throw new RuntimeException(skuChange.getSkuId()+"的库存不足");
            }
        });
        //处理prod库存
        prodData.forEach(prodChange -> {
            Integer i = prodMapper.changeProdStock(prodChange.getProdId(), prodChange.getCount());
            if (i == 0){
                throw new RuntimeException(prodChange.getProdId()+"的库存不足");
            }
        });
    }

    /**
     * 新增商品
     * 1.设置一些默认值
     * 2.写prod表
     * 3.写sku表
     * 4.写tag_reference 表
     * @param prod
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(Prod prod) {
        prod.setUpdateTime(new Date());
        prod.setCreateTime(new Date());
        //状态控制上架还是下架
        if (prod.getStatus().equals(1)){
            //上架
            prod.setPutawayTime(new Date());
        }
        prod.setVersion(0);
        prod.setShopId(1L);
        prod.setSoldNum(0);
        //拿到配置对象
        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        prod.setDeliveryMode(JSON.toJSONString(deliveryModeVo));
        int i = prodMapper.insert(prod);
        if (i>0){
            handleSku(prod.getProdId(), prod.getSkuList());
            handleTagReference(prod.getProdId(), prod.getTagList());
        }
        return false;
    }

    /**
     * 处理商品新增的标签分组
     * @param prodId
     * @param tagList
     */
    private void handleTagReference(Long prodId, List<Long> tagList) {
        if (CollectionUtils.isEmpty(tagList)){
            return;
        }
        ArrayList<ProdTagReference> ProdTagReferences = new ArrayList<>(tagList.size());
        tagList.forEach(tagId->{
            ProdTagReference prodTagReference = new ProdTagReference();
            prodTagReference.setCreateTime(new Date());
            prodTagReference.setProdId(prodId);
            prodTagReference.setTagId(tagId);
            prodTagReference.setShopId(1L);
            prodTagReference.setStatus(true);
            ProdTagReferences.add(prodTagReference);
        });
        prodTagReferenceService.saveBatch(ProdTagReferences);
    }

    /**
     * 处理商品新增的sku
     * @param prodId
     * @param skuList
     */
    private void handleSku(Long prodId, List<Sku> skuList) {
        if (CollectionUtils.isEmpty(skuList)){
            return;
        }
        skuList.forEach(sku -> {
            sku.setProdId(prodId);
            sku.setVersion(0);
            sku.setUpdateTime(new Date());
            sku.setRecTime(new Date());
            sku.setStatus(1);
            sku.setActualStocks(sku.getStocks());
        });
        skuService.saveBatch(skuList);
    }
}
